<?php

namespace App\Http\Controllers\Api;

use App\Models\Admin;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    // 教师登录
    public function teacherLogin(Request $request)
    {
        // 验证参数
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        // 查找教师
        $teacher = Admin::where('username', $request->username)->first();

        // 检查账号状态
        if ($teacher && $teacher->status == 0) {
            return $this->error('该账号已停用，请联系管理员', 500);
        }

        // 验证密码
        if (!$teacher || !Hash::check($request->password, $teacher->password)) {
            return $this->error('教师用户名或密码错误', 500);
        }

        // 生成令牌（清除旧令牌）
        $teacher->tokens()->delete();
        $token = $teacher->createToken('teacher_token')->plainTextToken;

        $data = [
            'user' => [
                'id' => $teacher->id,
                'username' => $teacher->username,
                'role' => 'teacher'
            ],
            'token' => $token
        ];

        return $this->success($data);
    }

    // 学生登录
    public function studentLogin(Request $request)
    {
        // 验证参数
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        // 查找学生
        $student = Student::where('username', $request->username)->first();

        // 检查账号状态
        if ($student && $student->status == 0) {
            return $this->error('该账号已停用，请联系管理员', 500);
        }

        // 验证密码
        if (!$student || !Hash::check($request->password, $student->password)) {
            return $this->error('学生用户名或密码错误', 500);
        }

        // 生成令牌（清除旧令牌）
        $student->tokens()->delete();
        $token = $student->createToken('student_token')->plainTextToken;

        $data = [
            'user' => [
                'id' => $student->id,
                'username' => $student->username,
                'role' => 'student'
            ],
            'token' => $token
        ];

        return $this->success($data);
    }

    // 退出登录
    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();
        return $this->success(null, '退出成功');
    }
}